<!--用户管理页-->
<template>
  <a-layout>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <a-form layout="inline" :model="param">
        <a-form-item>
          <a-input v-model:value="param.name" placeholder="登录名"/>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleQuery({pageNum: 1, pageSize: pagination.pageSize})">
            查询
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="add()">
            新增
          </a-button>
        </a-form-item>
      </a-form>
      <a-table
          :columns="columns"
          :row-key="record => record.id"
          :data-source="users"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
      >
        <template #cover="{ text: cover }">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>
        <template v-slot:category="{text, record}">
          {{ getCategoryName(text.category1Id) }} / {{ getCategoryName(text.category2Id) }}
        </template>
        <template v-slot:action="{ text, record }">
          <a-space size="small">
            <a-button type="primary" @click="resetPassword(record)">
              重置密码
            </a-button>
            <a-button type="primary" @click="edit(record)">
              编辑
            </a-button>
            <a-popconfirm
                title="删除后不可恢复，确认删除？"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record.id)"
            >
              <a-button danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <!-- 编辑 -->
  <a-modal v-model:visible="modalVisible" title="用户表单" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form
        :model="user"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
    >
      <a-form-item label="登录名">
        <!-- !!表示去掉类型检查 -->
        <a-input v-model:value="user.loginName" :disabled="!!user.id"/>
      </a-form-item>
      <a-form-item label="昵称">
        <a-input v-model:value="user.name"/>
      </a-form-item>
      <a-form-item label="密码" v-show="!user.id">
        <a-input v-model:value="user.password"/>
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 重置密码 -->
  <a-modal v-model:visible="resetModalVisible" title="重置密码" :confirm-loading="resetConfirmLoading" @ok="handleResetOk">
    <a-form
        :model="user"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
    >
      <a-form-item label="密码">
        <a-input v-model:value="user.password"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts">
import {SmileOutlined, DownOutlined} from '@ant-design/icons-vue';
import {defineComponent, onMounted, ref} from 'vue';
import axios from "axios";
import {message} from "ant-design-vue";
import {Tool} from "@/util/tool";

// 声明md5 方法 加盐（比如123->abc,那么123abc->sjdhf 加盐后简单的密码更难破解）
declare let hexMd5: any;
declare let KEY: any;

export default defineComponent({
  name: 'admin-user',
  components: {
    SmileOutlined,
    DownOutlined,
  },
  setup() {
    const users = ref();
    // 用户查询参数封装
    const param = ref();
    param.value = {};
    const pagination = ref({
      current: 1,
      pageSize: 3,
      total: 0
    });
    const loading = ref(false);

    const columns = [
      {
        title: '登录名',
        dataIndex: 'loginName'
      },
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '密码',
        dataIndex: 'password'
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    /**
     * 数据查询
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 这里get传参不用拼接方法 使用params固定参数配置
      axios.get("/user/list", {
        params: {
          pageNum: params.pageNum,
          pageSize: params.pageSize,
          loginName: param.value.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          users.value = data.content.list;

          // 重置分页按钮
          pagination.value.current = params.pageNum;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }
      });
    }

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      console.log("看看自带的分页参数都有啥：" + JSON.stringify(pagination));
      handleQuery({
        pageNum: pagination.current,
        pageSize: pagination.pageSize
      });
    };

    // 弹出编辑框
    const modalVisible = ref(false);
    const confirmLoading = ref<boolean>(false);
    // --------表单数据-----------
    const user = ref();
    const edit = (record: any) => {
      modalVisible.value = true;
      // user.value = record; 此写法会是响应式的 编辑应该是编辑赋值的对象，通过JSON方法实现  这里封装成工具类
      // user.value = JSON.parse(JSON.stringify(record));
      user.value = Tool.copy(record);
    };

    // 编辑框确认
    const handleOk = () => {
      // 对密码进行md5加密
      user.value.password = hexMd5(user.value.password + KEY)
      confirmLoading.value = true;
      // 不像get,传params键
      axios.post("/user/save", user.value).then((resp) => {
        const data = resp.data;
        confirmLoading.value = false;
        // 成功
        if (data.success) {
          modalVisible.value = false;
          // 刷新列表
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize
          });
        } else {
          message.error(data.message);
        }
      })
    };

    // 弹出重置密码
    const resetModalVisible = ref(false);
    const resetConfirmLoading = ref<boolean>(false);
    const resetPassword = (record: any) => {
      resetModalVisible.value = true;
      // user.value = record; 此写法会是响应式的 编辑应该是编辑赋值的对象，通过JSON方法实现  这里封装成工具类
      // user.value = JSON.parse(JSON.stringify(record));
      user.value = Tool.copy(record);
      user.value.password = null;
    };
    // --------表单数据-----------
    // 密码编辑框确认
    const handleResetOk = () => {
      // 对密码进行md5加密
      user.value.password = hexMd5(user.value.password + KEY)
      resetConfirmLoading.value = true;
      // 不像get,传params键
      axios.post("/user/reset-password", user.value).then((resp) => {
        const data = resp.data;
        resetConfirmLoading.value = false;
        // 成功
        if (data.success) {
          resetModalVisible.value = false;
          // 刷新列表
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize
          });
        } else {
          message.error(data.message);
        }
      })
    };

    // 新增用户
    const add = () => {
      modalVisible.value = true;
      user.value = {};
    };
    const handleDelete = (id: number) => {
      axios.delete("/user/delete/" + id).then((resp) => {
        const data = resp.data;
        // 成功
        if (data.success) {
          // 刷新列表
          handleQuery({
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize
          });
        }
      })
    }

    onMounted(() => {
      handleQuery({
        pageNum: 1,
        pageSize: pagination.value.pageSize,
      });
    });

    return {
      users,
      param,
      pagination,
      loading,
      handleTableChange,
      columns,
      user,
      modalVisible,
      confirmLoading,
      edit,
      add,
      handleOk,
      handleDelete,
      handleQuery,
      resetModalVisible,
      resetConfirmLoading,
      handleResetOk,
      resetPassword
    };
  },
});
</script>


<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>